package com.hyk.commonLib.common.adapter;

import androidx.annotation.CallSuper;

import com.hyk.commonLib.common.utils.ListUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public abstract class BaseSelectAdapter<VH extends BaseViewHolder<?, ?>, ITEM> extends BaseAdapter<VH, ITEM> {

    protected List<Boolean> checkStateList = new ArrayList<>();

    @CallSuper
    @Override
    public BaseSelectAdapter<VH, ITEM> insertItemList(List<ITEM> itemList, int position) {
        checkStateList.addAll(position, getFalseList(itemList.size()));
        super.insertItemList(itemList, position);
        return this;
    }

    @CallSuper
    @Override
    public BaseSelectAdapter<VH, ITEM> addItemList(List<ITEM> itemList) {
        checkStateList.addAll(getFalseList(itemList.size()));
        super.addItemList(itemList);
        return this;
    }

    @CallSuper
    @Override
    public BaseSelectAdapter<VH, ITEM> setItemList(List<ITEM> itemList) {
        checkStateList.clear();
        checkStateList.addAll(getFalseList(itemList.size()));
        setChecked(0);
        super.setItemList(itemList);
        return this;
    }

    @CallSuper
    @Override
    public BaseSelectAdapter<VH, ITEM> removeItem(int position) {
        checkStateList.remove(position);
        if (ListUtils.notEmpty(checkStateList) && ListUtils.isEmpty(getCheckedItemPositionList())) {
            setChecked(0);
        }
        super.removeItem(position);
        return this;
    }

    public boolean isChecked(int position) {
        return checkStateList.get(position);
    }

    public List<Integer> getCheckedItemPositionList() {
        List<Integer> checkedItemPositionList = new ArrayList<>();
        for (int i = 0; i < checkStateList.size(); i++) {
            if (checkStateList.get(i)) {
                checkedItemPositionList.add(i);
            }
        }
        return checkedItemPositionList;
    }

    public List<ITEM> getCheckedItemList() {
        List<ITEM> checkedItemList = new ArrayList<>();
        for (int i = 0; i < checkStateList.size(); i++) {
            if (checkStateList.get(i)) {
                checkedItemList.add(getItem(i));
            }
        }
        return checkedItemList;
    }

    public void setCheckState(int position, boolean checkState) {
        if (checkStateList.get(position) == checkState) return;
        checkStateList.set(position, checkState);
        notifyItemChanged(position);
    }

    public void setChecked(int position) {
        setCheckState(position, true);
    }

    public void setUnchecked(int position) {
        setCheckState(position, false);
    }

    private List<Boolean> getFalseList(int size) {
        return Stream.iterate(false, b -> false).limit(size).collect(Collectors.toList());
    }
}
